<template>
  <ContainerContent
    :loading="loading"
    :pagination="pagination"
    @run="run"
    inner>
    <template #header>
      <a-button type="primary" @click="open()">
        <i-icons-btn-add />
        创建规则
      </a-button>
      <CloudFilterBar v-model="params" :run="run" :schemes="filterSchemes" />
    </template>
    <a-table
      ref="tableRef"
      v-bind="commonTableProps"
      :columns="columns"
      :data="data"
      row-key="id"
      @sorter-change="onSorterChange">
      <template #sort>
        <i-icons-draggable class="drag-icon" />
      </template>
      <template #execution="{ record }">
        <section class="flex items-center gap-x-1">
          <i-icons-prevent v-if="record.action === A_EXECUTION_TYPE.PREVENT" />
          <i-icons-observe v-if="record.action === A_EXECUTION_TYPE.OBSERVE" />
          <i-icons-js v-if="record.action === A_EXECUTION_TYPE.JS" />
          <i-icons-inquiry
            v-if="record.action === A_EXECUTION_TYPE.INTERACTIVE" />
          {{ getOptionsLabel(customOptions, record.action) }}
        </section>
      </template>
      <template #status="{ record }">
        <a-switch
          :model-value="record.status"
          :checked-value="1"
          :unchecked-value="2"
          size="small"
          :before-change="
            (val: number) => handleBeforeChange(val, record)
          "></a-switch>
      </template>
      <template #action="{ record }">
        <a-link :hoverable="false" @click="open(record)"> 编辑 </a-link>
        <a-link status="danger" :hoverable="false" @click="handDelete(record)">
          删除
        </a-link>
      </template>
    </a-table>
    <add-rule-dialog
      v-model:visible="visible"
      :record="ruleData"
      :id="id"
      @refresh="run" />
  </ContainerContent>
</template>
<script lang="ts" setup>
import type { WafListItem } from '@/apis/model/waf'
import {
  deleteApiWafApi,
  getApiWafQueryApi,
  updateApiWafPriorityApi,
  updateApiWafStatusApi
} from '@/apis/modules/waf'
import ContainerContent from '@/components/ContentContainer.vue'
import type { CloudFilterBarState } from '@/components/filter-bar/types'
import { A_EXECUTION_TYPE } from '@/constants'
import { commonTableProps } from '@/utils/table'
// import type { TableChangeExtra, TableData } from '@arco-design/web-vue'
import Sortable from 'sortablejs'
import AddRuleDialog from './AddRuleDialog.vue'
import useTableColumn from './column'
import { useConfigStore } from '@/stores/config'
const route = useRoute()
const tableRef = ref()
const id = computed(() => route.params.id as string)
const params = ref<CloudFilterBarState>({
  order: 'asc',
  sort: 'priority',
  scope: 2,
  module: 1,
  action: 0,
  bind_id: id.value
})
const { visible, open, data: ruleData } = usePopup()
const { columns, filterSchemes } = useTableColumn()
const { data, loading, run, pagination } = useListRequest(getApiWafQueryApi, {
  params,
  immediate: false
})
const { createSortChange } = useTable(run, data)
const onSorterChange = createSortChange(params)

// const handleDragChange = async (
//   _data: TableData[],
//   extra: TableChangeExtra,
//   currentData: TableData[]
// ) => {
// currentData = currentData.map((item) => item.raw)
// const { id, targetData } = findOrderChanges(
//   data.value,
//   currentData,
//   extra.dragTarget.id
// )
// await updateApiWafPriorityApi({ id, priority: targetData.priority })
// ToastUtils.success('操作成功')
// run()
// }

const handleBeforeChange = (status: number, row: WafListItem) => {
  return new Promise((resolve, reject) => {
    updateApiWafStatusApi({ id: row.id, status } as any)
      .then(() => {
        row.status = row.status === 1 ? 2 : 1
        resolve(void 0)
      })
      .finally(() => reject(false))
  })
}
const handDelete = (row: any) => {
  CloudModal.error(
    {
      content: `确认删除规则 “${row?.name}” ？`,
      okText: '删除'
    },
    async () => {
      await deleteApiWafApi({ id: row?.id })
      ToastUtils.success('操作成功')
      run!()
    }
  )
}
watchEffect(() => {
  run({ bind_id: id.value })
})
const changeRule = async (id: string, priority: number) => {
  await updateApiWafPriorityApi({ id, priority })
  ToastUtils.success('操作成功')
  run()
}
onMounted(async () => {
  const customRulesId = localStorage.getItem('customRulesId')
  if (customRulesId) {
    params.value.id = customRulesId
    localStorage.setItem('customRulesId', '')
    localStorage.setItem('logModule', '')
  }
  await nextTick()
  const el = (tableRef.value.$el as HTMLElement).querySelector('tbody')
  Sortable.create(el, {
    animation: 300,
    //设置指定列作为拖拽
    handle: '.drag-icon',
    forceFallBack: true,
    onEnd(evt: { newIndex: number; oldIndex: number }) {
      const { newIndex, oldIndex } = evt
      if (newIndex === oldIndex) {
        return
      }
      const id = data.value[oldIndex].id!
      const priority = data.value[newIndex].priority!
      changeRule(id, priority)
    }
  })

  useConfigStore().getCondition({ module: 1 })
})
</script>

<style lang="less" scoped></style>
